package org.nfyszny.zzzs.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.nfyszny.zzzs.modules.constant.CertificateConstant;
import org.nfyszny.zzzs.modules.constant.ExamineConstant;
import org.nfyszny.zzzs.modules.constant.ReCordConstant;
import org.nfyszny.zzzs.modules.entity.*;
import org.nfyszny.zzzs.modules.mapper.ZzzsRecordOfSupplyAbilityMapper;
import org.nfyszny.zzzs.modules.service.IZzzsCertificateService;
import org.nfyszny.zzzs.modules.service.IZzzsExamineService;
import org.nfyszny.zzzs.modules.service.IZzzsProductRecordingService;
import org.nfyszny.zzzs.modules.service.IZzzsRecordOfSupplyAbilityService;
import org.nfyszny.zzzs.modules.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Description: 供货能力备案
 * @Author: jeecg-boot
 * @Date: 2022-11-11
 * @Version: V1.0
 */
@Service
public class ZzzsRecordOfSupplyAbilityServiceImpl extends ServiceImpl<ZzzsRecordOfSupplyAbilityMapper, ZzzsRecordOfSupplyAbility> implements IZzzsRecordOfSupplyAbilityService {
    @Autowired
    private IZzzsProductRecordingService productRecordingService;
    @Autowired
    private ISysDepartService departService;
    @Autowired
    private ISysUserDepartService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    @Lazy
    private IZzzsExamineService examineService;
    @Autowired
    private IZzzsCertificateService certificateService;

    @Override
    public Map<String, Object> getStateAbility(String productId) {
        System.out.println("productId = " + productId);
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<ZzzsRecordOfSupplyAbility> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);

        List<ZzzsRecordOfSupplyAbility> zzzsRecordOfSupplyAbility = baseMapper.selectList(queryWrapper);
        if (zzzsRecordOfSupplyAbility.size() == 0) {
            map.put("status", true);
        } else {
            //过滤状态为审核失败的条数
            List<ZzzsRecordOfSupplyAbility> collect = zzzsRecordOfSupplyAbility.stream().filter(item -> {
                if (item.getStatus() == ReCordConstant.RecordEnum.RECORD_ERROR.getCode()) {
                    return true;
                }
                return false;
            }).collect(Collectors.toList());
            map.put("status", collect.size() != 0);
            List<ZzzsRecordOfSupplyAbility> createList = zzzsRecordOfSupplyAbility.stream().filter(item -> {
                if (item.getStatus() == ReCordConstant.RecordEnum.RECORD_CREATE.getCode()) {
                    return true;
                }
                return false;
            }).collect(Collectors.toList());
            System.out.println("createList = " + createList);
            //如果有记录则证明处于新建状态
            if (createList.size() != 0) {
                map.put("result", createList.get(0));
                map.put("status", true);
            }
        }
        return map;

    }

    @Override
    public IPage<ZzzsRecordOfSupplyAbility> getListByProductId(QueryWrapper<ZzzsRecordOfSupplyAbility> queryWrapper, Page<ZzzsRecordOfSupplyAbility> page) {
        QueryWrapper<ZzzsProductRecording> wrapper = new QueryWrapper<>();
        LoginUser userInfo = UserUtils.getUserInfo();
        wrapper.eq("sys_org_code", userInfo.getOrgCode());

        Page<ZzzsRecordOfSupplyAbility> page1 = page(page, queryWrapper);


        return page1;
    }

    @Override
    public void saveRecordOfSupplyAbility(ZzzsRecordOfSupplyAbility zzzsRecordOfSupplyAbility) {
        zzzsRecordOfSupplyAbility.setStatus(ReCordConstant.RecordEnum.RECORD_CREATE.getCode());
        zzzsRecordOfSupplyAbility.setIsDelete(ReCordConstant.iterationEnum.LOGOUT_YES.getCode());
        baseMapper.insert(zzzsRecordOfSupplyAbility);
    }

    @Transactional
    @Override
    public void submitRecord(ZzzsRecordOfSupplyAbility zzzsRecordOfSupplyAbility) {
        zzzsRecordOfSupplyAbility.setStatus(ReCordConstant.RecordEnum.RECORD_CHECK.getCode());
        zzzsRecordOfSupplyAbility.setIsDelete(ReCordConstant.iterationEnum.LOGOUT_YES.getCode());
        
        saveOrUpdate(zzzsRecordOfSupplyAbility);
        //分配审批人
        LoginUser userInfo = UserUtils.getUserInfo();
        SysDepart sysDepart = departService.queryCompByOrgCode(userInfo.getOrgCode());
        List<SysDepart> sysDeparts = departService.queryDeptByPid(sysDepart.getId());
        //找出监管部门
        SysDepart sysDepart1 = sysDeparts.stream().filter(item -> {
            return item.getOrgCategory().equals("3");
        }).findAny().get();
        SysUserDepart user = userService.getUserByDeptId(sysDepart1.getId());
        if (user != null) {
            zzzsRecordOfSupplyAbility.setApproverId(user.getUserId());
        }
        //在审批表中插入记录
        ZzzsExamine zzzsExamine = new ZzzsExamine();
        zzzsExamine.setRecordId(zzzsRecordOfSupplyAbility.getId());
        zzzsExamine.setRecordType(ExamineConstant.RecordType.CAPACITY_OF_EFFICACY_RECORD.getCode());
        zzzsExamine.setExaminePerson(user.getUserId());
        zzzsExamine.setExamineStatus(ExamineConstant.StatusEnum.CHECK_STATUS.getCode());

        examineService.save(zzzsExamine);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //过期前30分钟基于提醒
        redisTemplate.opsForValue().set(zzzsExamine.getId() + "_" + format.format(new Date()) + "_" + user.getUserId() + "_供销能力_message", "", 2 * 24 * 60 - 30, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(zzzsExamine.getId() + "_" + format.format(new Date()) + "_" + user.getUserId() + "_供销能力_exceed", "", 2, TimeUnit.DAYS);
    }

    @Override
    @Transactional
    public void change(ZzzsRecordOfSupplyAbility zzzsRecordOfSupplyAbility) {
        //先将上一条备案信息隐藏
        ZzzsRecordOfSupplyAbility record = new ZzzsRecordOfSupplyAbility();
        record.setId(zzzsRecordOfSupplyAbility.getId());
        record.setIsDelete(ReCordConstant.iterationEnum.LOGOUT_NO.getCode());
        System.out.println("record = " + record);
        int i = baseMapper.updateIsDeleteById(record);
        System.out.println("i = " + i);
        //再将重新备案的id设置为null
        zzzsRecordOfSupplyAbility.setId(null);
        this.submitRecord(zzzsRecordOfSupplyAbility);
        //将证书表对应的备案id改成新的备案id
        ZzzsCertificate certificate = certificateService.getOne(new QueryWrapper<ZzzsCertificate>().eq("certificate_id", record.getId()));

        certificate.setCertificateId(zzzsRecordOfSupplyAbility.getId());
        certificate.setStatus(CertificateConstant.CertificateStatus.INVALID.getCode());
        certificateService.updateById(certificate);


    }

    @Override
    @Transactional
    public void review(ZzzsRecordOfSupplyAbility zzzsRecordOfSupplyAbility) {
        //先将上一条备案信息隐藏
        ZzzsRecordOfSupplyAbility record = new ZzzsRecordOfSupplyAbility();
        record.setId(zzzsRecordOfSupplyAbility.getId());
        record.setIsDelete(ReCordConstant.iterationEnum.LOGOUT_NO.getCode());
        System.out.println("record = " + record);
        int i = baseMapper.updateIsDeleteById(record);
        System.out.println("i = " + i);
        //再将重新备案的id设置为null
        zzzsRecordOfSupplyAbility.setId(null);
        this.submitRecord(zzzsRecordOfSupplyAbility);
        //将证书表对应的备案id改成新的备案id
        ZzzsCertificate certificate = certificateService.getOne(new QueryWrapper<ZzzsCertificate>().eq("certificate_id", record.getId()));

        certificate.setCertificateId(zzzsRecordOfSupplyAbility.getId());
        certificate.setStatus(CertificateConstant.CertificateStatus.GIVEN_OUT.getCode());
        certificateService.updateById(certificate);


    }

    @Override
    public ZzzsRecordOfSupplyAbility getHaveInfoById(String id) {

        return baseMapper.getHaveInfoById(id);
    }

}
